package com.ruoyi.lxy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.lxy.domain.bo.TProjectBo;
import com.ruoyi.lxy.domain.vo.TProjectVo;
import com.ruoyi.lxy.domain.TProject;
import com.ruoyi.lxy.mapper.TProjectMapper;
import com.ruoyi.lxy.service.ITProjectService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 项目Service业务层处理
 *
 * @author ruoyi
 * @date 2023-08-24
 */
@RequiredArgsConstructor
@Service
public class TProjectServiceImpl implements ITProjectService {

    private final TProjectMapper baseMapper;

    /**
     * 查询项目
     */
    @Override
    public TProjectVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询项目列表-管理员|超级管理员
     */
    @Override
    public TableDataInfo<TProjectVo> queryPageList(TProjectBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TProject> lqw = buildQueryWrapper(bo);
        Page<TProjectVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<TProjectVo> transformedList = new ArrayList<>();
        for (TProjectVo projectVo : result.getRecords()) {
            transformedList.add(StatusTransitionVo(projectVo));
        }
        //转换后的值设置回Page对象
        result.setRecords(transformedList);
        return TableDataInfo.build(result);
    }

    /**
     * 查询项目列表-|旅行社
     */
    @Override
    public TableDataInfo<TProjectVo> TravellagenqueryPageList(TProjectBo bo, PageQuery pageQuery) {
        //获取当前登录用户的旅行社ID
        Long TravellagenId = LoginHelper.getLoginUser().getUserId();
        //根据旅行社ID查询其参与的项目ID
        List<Long> projectIds = baseMapper.selectProjectListByAgencyId(TravellagenId);
        //构建查询条件,根据项目IDList查询项目并分页,且项目状态为未开始或进行中
        LambdaQueryWrapper<TProject> lqw = Wrappers.lambdaQuery();
        lqw.in(TProject::getId,projectIds);
        lqw.eq(TProject::getStatusCode,0).or().eq(TProject::getStatusCode,1);
        Page<TProjectVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<TProjectVo> transformedList = new ArrayList<>();
        for (TProjectVo projectVo : result.getRecords()) {
            transformedList.add(StatusTransitionVo(projectVo));
        }
        //转换后的值设置回Page对象
        result.setRecords(transformedList);
        return TableDataInfo.build(result);
    }


    /**
     * 查询项目列表
     */
    @Override
    public List<TProjectVo> queryList(TProjectBo bo) {
        LambdaQueryWrapper<TProject> lqw = buildQueryWrapper(bo);
        /*  将状态转换为string返回*/
        List<TProjectVo> projectVos = baseMapper.selectVoList(lqw).stream().map(
            this::StatusTransitionVo).collect(Collectors.toList());
        return projectVos;
    }

    /**
     * 根据旅行社ID获取项目选择框列表
     */
    @Override
    public List<Long> selectProjectListByAgencyId(Long id) {
        return baseMapper.selectProjectListByAgencyId(id);
    }
    /**
     * 根据旅行社ID查询项目列表
     */
    @Override
    public List<TProjectVo> selectProjectsByAgencyId(Long id){
        List<Long> agencyProjectIds = baseMapper.selectProjectListByAgencyId(id);
        List<TProjectVo> projects = queryList(new TProjectBo());
        for (TProjectVo project : projects) {
            for (Long agencyProjectId  : agencyProjectIds ) {
                if (project.getId().longValue() == agencyProjectId.longValue()) {
                    project.setFlag(true);
                    break;
                }
            }
        }
        return projects;
    }

    private LambdaQueryWrapper<TProject> buildQueryWrapper(TProjectBo bo) {
        TProjectBo tProjectBo = StatusTransitionBo(bo);
        Map<String, Object> params = tProjectBo.getParams();
        LambdaQueryWrapper<TProject> lqw = Wrappers.lambdaQuery();
        lqw.like(tProjectBo.getYear() != null, TProject::getYear, tProjectBo.getYear());
        lqw.like(StringUtils.isNotBlank(tProjectBo.getName()), TProject::getName, tProjectBo.getName());
        //状态转换，便于数据库查询
        lqw.eq(tProjectBo.getStatusCode()!=null, TProject::getStatusCode, tProjectBo.getStatusCode());
        return lqw;
    }

    /**
     * 状态转换
     */
    private TProjectBo StatusTransitionBo(TProjectBo bo) {
        if (bo.getStatus() != null)
            switch (bo.getStatus()) {
                case "未开始":
                    bo.setStatusCode(0);
                    break;
                case "进行中":
                    bo.setStatusCode(1);
                    break;
                case "已结束":
                    bo.setStatusCode(2);
                    break;
            }
        return bo;
    }
    private TProjectVo StatusTransitionVo(TProjectVo projectVo) {
        if (projectVo.getStatusCode() != null)
            switch (projectVo.getStatusCode()) {
                case 0:
                    projectVo.setStatus("未开始");
                    break;
                case 1:
                    projectVo.setStatus("进行中");
                    break;
                case 2:
                    projectVo.setStatus("已结束");
                    break;
            }
        return projectVo;
    }
    /**
     * 新增项目
     */
    @Override
    public Boolean insertByBo(TProjectBo bo) {
        TProjectBo tProjectBo = StatusTransitionBo(bo);
        TProject add = BeanUtil.toBean(tProjectBo, TProject.class);
        validEntityBeforeSave(add,0);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            tProjectBo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改项目
     */
    @Override
    public Boolean updateByBo(TProjectBo bo) {
        TProjectBo tProjectBo = StatusTransitionBo(bo);
        TProject update = BeanUtil.toBean(tProjectBo, TProject.class);
        validEntityBeforeSave(update,1);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TProject entity,Integer code) {
        //TODO 做一些数据校验,如唯一约束
        if (code == 0) {
            if (!projectVerify(entity,0)) {
                throw new IllegalArgumentException("已存在未开始或进行中的项目");
            }
        } else if (code == 1) {
            if (!projectVerify(entity,1)) {
                throw new IllegalArgumentException("已存在未开始或进行中的项目");
            }
        }

    }
    /*
    校验项目是否可以更新或插入，保证只有一个项目处于未开始和进行中状态。
       0 代表新增，1 代表修改
     */

    public Boolean projectVerify(TProject project,Integer code){
        List<TProject> projects = baseMapper.selectList(null);
        if (code == 0) {
            for (TProject project1 : projects) {
                if (project1.getStatusCode() == 0 || project1.getStatusCode() == 1) {
                    return false;
                }
            }
        } else if (code == 1) {
            for (TProject project1 : projects) {
                if (project1.getStatusCode() == 0 || project1.getStatusCode() == 1) {
                    if (project1.getId().longValue() != project.getId().longValue()) {
                        return false;
                    }
                }
            }
        }
        return true;
    }
    /**
     * 批量删除项目
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

}
